<template>
  <div class="dev-view">
    <div class="search-row" style="margin-bottom: 10px;">
      <div>
        <div class="item">
          <label>
            <i class="el-icon-folder-opened"></i>
            <span>通道</span>
          </label>
          <el-select v-model="curWay" size="small" placeholder="请选择通道" @change="handleChange">
            <el-option
              v-for="item in wayList"
              :key="item.channelid"
              :label="item.channelname"
              :value="item.channelid"
            />
          </el-select>
        </div>
      </div>
    </div>
    <c-card v-loading="loading" title="设备列表" class="sb-wrapper">
      <el-button slot="func" type="primary" :disabled="!curWay" size="small" @click="addDev">添加设备</el-button>
      <template v-if="!curWay">
        <h3>请选择通道</h3>
      </template>
      <template v-else>
        <el-table :data="tableData" style="width: 100%">
          <el-table-column prop="deviceid" label="序号">
            <template v-slot="{$index}">{{ $index + 1 }}</template>
          </el-table-column>
          <el-table-column prop="name" label="设备名称" show-overflow-tooltip></el-table-column>
          <el-table-column label="操作">
            <template v-slot="{row, $index}">
              <el-button size="small" type="text" @click="editDev(row)">编辑</el-button>
              <el-button size="small" type="text" @click="showParamsDlg(row)">查看数据</el-button>
              <el-button size="small" type="text" @click="deleteDev(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </c-card>
    <!-- 编辑设备 -->
    <c-dlg
      v-if="curDevInfo"
      :visible.sync="showDlg"
      :title="curDev ? '编辑设备' : '添加设备'"
      @close="showDlg = false"
    >
      <el-form ref="curDevInfo" :model="curDevInfo" :rules="rules" label-width="60px" class="demo-ruleForm" label-position="top">
        <div class="form-row">
          <div class="row-item">
            <el-form-item label="设备名称" prop="name">
              <el-input v-model="curDevInfo.name" size="small" placeholder="请输入" />
            </el-form-item>
          </div>
          <spliter />
          <div class="row-item">
            <el-form-item label="设备地址" prop="deviceaddr">
              <el-input v-model="curDevInfo.deviceaddr" type="number" max-length="9" size="small" placeholder="请输入数字" />
            </el-form-item>
          </div>
        </div>
        <div class="form-row">
          <div class="row-item">
            <el-form-item label="所属通道" prop="channel">
              <el-select v-model="curDevInfo.channel" size="small" placeholder="请选择通道">
                <el-option
                  v-for="item in wayList"
                  :key="item.channelid"
                  :label="item.channelname"
                  :value="item.channelid"
                ></el-option>
              </el-select>
            </el-form-item>
          </div>
          <spliter />
          <div class="row-item">
            <el-form-item label="设备组" prop="devicegroupid">
              <el-select
                v-model="curDevInfo.devicegroupid"
                size="small"
                placeholder="请选择"
                @change="groupChange"
              >
                <el-option
                  v-for="g in groups"
                  :key="g.pkid"
                  :value="g.pkid"
                  :label="g.devgroupname"
                ></el-option>
              </el-select>
            </el-form-item>
          </div>
        </div>
        <div class="form-row">
          <div class="row-item">
            <el-form-item label="所属区域" prop="parentarea">
              <el-select v-model="curDevInfo.parentarea" size="small" placeholder="请选择所属区域">
                <el-option v-for="item in areas" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </div>
          <spliter />
          <div class="row-item">
            <el-form-item label="设备模版" prop="devicetempid">
              <el-select
                v-model="curDevInfo.devicetempid"
                size="small"
                placeholder="请输入"
                @change="tplChange"
              >
                <el-option
                  v-for="item in devTpls"
                  :key="item.devtempid"
                  :label="item.devtempname"
                  :value="item.devtempid"
                ></el-option>
              </el-select>
            </el-form-item>
          </div>
        </div>
        <div class="form-row">
          <div class="row-item">
            <el-form-item label="设备扩展地址" prop="addressex">
              <el-input v-model="curDevInfo.addressex" size="small" type="number" placeholder="请输入"></el-input>
            </el-form-item>
          </div>
          <spliter />
          <div class="row-item">
            <el-form-item label="设备子系列" prop="devicetempserialid">
              <el-select v-model="curDevInfo.devicetempserialid" size="small" placeholder="请输入">
                <el-option
                  v-for="item in devChildren"
                  :key="item.devtempserialid"
                  :label="item.devtempserialname"
                  :value="item.devtempserialid"
                ></el-option>
              </el-select>
            </el-form-item>
          </div>
        </div>
        <div class="form-row">
          <div class="row-item">
            <el-form-item label="优先级数目" prop="prioritylevel">
              <el-select v-model="curDevInfo.prioritylevel" placeholder="请选择">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </div>
          <spliter />
          <div class="row-item"></div>
        </div>
      </el-form>
      <div slot="footer">
        <el-button type="danger" size="small" @click="saveDevInfo(('curDevInfo'))">保存</el-button>
        <el-button size="small" @click="cancleSave">取消</el-button>
      </div>
    </c-dlg>

    <!-- 查看数据 -->
    <c-dlg :visible.sync="paramsVisible" mask title="数据列表" @close="showType = '';">
      <el-table :data="paramsList" border style="width: 800px" size="small" height="491">
        <el-table-column prop="variablename" label="数据名称" />
        <!-- <el-table-column prop="variabletype" label="数据类型">
          <template v-slot="{row}">{{ getVarType(row.variabletype) }}</template>
        </el-table-column> -->
        <el-table-column prop="variabletype" label="数据类别"></el-table-column>
        <el-table-column prop="ratio" label="转换系数" />
        <el-table-column prop="length" label="数据长度" />
        <el-table-column prop="rcAddressStr" label="遥控基数据" />
        <el-table-column label="操作" width="120">
          <template v-slot="{row}">
            <el-button size="small" type="text" @click="editData(row)">编辑</el-button>
            <el-button size="small" type="text" @click="deleteData(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          layout="prev, pager, next"
          :total="page.total"
          :current-page.sync="page.index"
          @current-change="getParams"
        />
      </div>
    </c-dlg>

    <!-- 未知 -->
    <c-dlg v-if="newData" title="编辑数据项" :visible.sync="dataDlg" @close="dataDlg = false">
      <el-form :model="newData" :rules="dataRules" label-width="60px" label-position="top">
        <div class="form-row">
          <div class="row-item">
            <el-form-item label="数据名:" prop="variablename">
              <el-input v-model="newData.variablename" size="small" placeholder="请输入" />
            </el-form-item>
          </div>
          <spliter />
          <div class="row-item">
            <el-form-item label="数据编码:" prop="datacodeid">
              <el-select v-model="newData.datacodeid" size="small" placeholder="请输入">
                <el-option
                  v-for="item in varCodes"
                  :key="+item.no"
                  :label="item.name"
                  :value="+item.no"
                ></el-option>
              </el-select>
            </el-form-item>
          </div>
        </div>
        <div class="form-row">
          <div class="row-item">
            <el-form-item label="数据类别:" prop="variabletype">
              <!-- <el-select v-model="newData.variabletype" size="small" placeholder="请输入">
                <el-option
                  v-for="item in varTypes"
                  :key="item.variabletype"
                  :label="item.variablename"
                  :value="item.variabletype"
                ></el-option>
              </el-select> -->
              <el-cascader v-model="newData.variabletype" :options="varTypes" :show-all-levels="false" clearable></el-cascader>
            </el-form-item>
          </div>
          <spliter />
          <div class="row-item">
            <el-form-item label="数据长度:" prop="length">
              <el-select v-model="newData.length" size="small" placeholder="请输入">
                <el-option
                  v-for="item in varLens"
                  :key="item.no"
                  :label="item.name"
                  :value="item.no"
                ></el-option>
              </el-select>
            </el-form-item>
          </div>
        </div>
        <div class="form-row">
          <div class="row-item">
            <el-form-item label="转换系数:" prop="ratio">
              <el-input v-model="newData.ratio" size="small" placeholder="请输入" />
            </el-form-item>
          </div>
          <spliter />
          <div class="row-item">
            <el-form-item label="采集类型:" prop="dctype">
              <el-select v-model="newData.dctype" size="small" placeholder="请输入">
                <el-option v-for="t in dctypes" :key="t.id" :value="t.name" :label="t.name"></el-option>
              </el-select>
            </el-form-item>
          </div>
        </div>
        <div class="form-row">
          <div class="row-item">
            <el-form-item label="遥控基数据" prop="rcAddressStr">
              <el-input v-model="newData.rcAddressStr" size="small" placeholder="请输入" />
            </el-form-item>
          </div>
          <spliter />
          <div class="row-item"></div>
        </div>
      </el-form>
      <div slot="footer">
        <el-button size="small" @click="saveData">确定</el-button>
        <el-button size="small" @click="dataDlg = false">取消</el-button>
      </div>
    </c-dlg>

  </div>
</template>

<script>
import { clone } from "lodash";
import CDlg from "@/components/CDlg";
import CCard from "@/components/CCard";
import Spliter from "@/components/Spliter";
import { editData, delData } from "@/api/front";
// import bus from '@/utils/bus'
export default {
  components: { CDlg, CCard, Spliter },
  props: {
    wayList: {
      type: Array,
      default() {
        return [];
      }
    }
  },
  data() {
    return {
      showDlg: false,
      paramsVisible: false,
      showType: "",
      curWay: null,
      curDev: null,
      loading: false,
      devInfo: {},
      curDevInfo: {
        channel: this.curWay || null,
        prioritylevel: 3,
        resendcount: 1,
        breakcount: 1,
        numareacount: 1
      },
      disabled: false,
      paramsList: null,
      page: {
        index: 1,
        size: 10,
        total: 0
      },
      // 下拉
      areas: null,
      groups: null,
      devTpls: null,
      devChildren: null,
      devTpls1: null,
      devChildren1: null,

      // data
      dataRules: {},
      newData: null,
      dataDlg: false,
      varTypes: null,
      varLens: null,
      varCodes: null,
      dctypes: null,
      // devList: []
      tableData: [],
      // 优先级数目
      options: [{
        value: 1,
        label: '主动上传'
      }, {
        value: 3,
        label: '被动召唤'
      }],
      value: '',
      rules: {
        name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
        ],
        deviceaddr: [
          { required: true, message: '设备地址不能为空且为数字', trigger: 'blur' },
          { pattern: /^[0-9]+$/, message: '设备为数字', trigger: 'blur' }
        ],
        channel: [
          { required: true, message: '请选择所属通道', trigger: 'change'}
        ],
        devicegroupid: [
          { required: true, message: '请选择设备组'}
        ],
        parentarea: [
          { required: true, message: '请选择所属区域'}
        ],
        devicetempid: [
          { required: true, message: '请选择设备模版'}
        ],
        addressex: [
          { required: true, message: '请输入设备扩展地址且为数字', trigger: 'blur' },
          { pattern: /^[0-9]+$/, message: '设备扩展地址为数字', trigger: 'blur' }
        ],
        devicetempserialid: [
          { required: true, message: '请选择设备子系列'}
        ],
        prioritylevel: [
          { required: true, message: '请选择优先级数目'}
        ]
      }
    };
  },
  computed: {
    // devList() {
    //   const a = this.wayList.filter(e => e.channelid === this.curWay)[0];
    //   console.log(a)
    //   if (a) {
    //     return a.nameVoList;
    //   } else {
    //     return [];
    //   }
    // },
    isEdit() {
      const back = this.devInfo[this.curDev];
      return JSON.stringify(back) !== JSON.stringify(this.curDevInfo);
    }
  },
  watch: {
    curWay(v) {
      const params = {
        channelId: v,
      };
      return this.$axios.get("fes/device/selectDev", { params }).then(res => {
        this.tableData = res.data;
      });
    }
  },
  created() {
    if (this.wayList && this.wayList.length > 0) {
      this.curWay = this.wayList[0].channelid;
    }
    this._getAreas();
    this._getGroup();
    // this._getDevChildren();
    // this._getDevTpls();
    // console.log('111', this.curWay)
  },
  mounted() {
    // this.getdev();
  },
  methods: {
    // 获取选择设备
    handleChange(e) {
      this.curWay = e
    },
    _getAreas() {
      return this.$axios.get("fes/drop/queryQymcxl").then(res => {
        this.areas = res.data;
      });
    },
    _getGroup() {
      return this.$axios.get("fes/device/threeDevgroup").then(res => {
        if (res.code === 1) {
          this.groups = res.data;
        }
      });
    },
    _getDevChildren(id) {
      const params = {
        devtempid: id,
        page: 1,
        rows: 100
      };
      return this.$axios.get("fes/device/getDevZxl", { params }).then(res => {
        this.devChildren = res.data.rows;
      });
    },
    getParams(id) {
      const params = {
        deviceId: this.curDevParam,
        page: this.page.index,
        rows: this.page.size
      };
      return this.$axios
        .get("fes/device/getCqname", { params })
        .then(res => {
          if (res.code === 1) {
            this.paramsList = res.data.rows;
            this.$set(this.page, "total", res.data.total);
          } else {
            throw res.msg;
          }
        })
        .catch(e => this.$message.error(e));
    },
    groupChange(v, init = false) {
      if (!init) {
        this.$set(this.curDevInfo, "devicetempid", null);
        this.$set(this.curDevInfo, "devicetempserialid", null);
      }
      const g = this.groups.filter(g => g.pkid === v)[0];
      this.devTpls = g ? g.list : null;
      this.devChildren = null;
    },
    tplChange(v, init = false) {
      this.$set(this.curDevInfo, "devicetempserialid", null);
      this._getDevChildren(v);
    },
    getDeviceInfo() {
      if (this.devInfo[this.curDev]) {
        this.curDevInfo = clone(this.devInfo[this.curDev]);
        return;
      }
      this.devLoading = true;
      const params = {
        channelid: this.curWay,
        deviceid: this.curDev
      };
      return this.$axios
        .get("fes/device/seeDev", { params })
        .then(res => {
          if (res.code === 1) {
            this.$set(this.devInfo, this.curDev, res.data);
            this.curDevInfo = clone(res.data);
          } else {
            this.$message.error(res.msg);
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    showDeleteDlg() {
      if (!this.curDev) {
        this.$message.warning("请先选择设备...");
        return;
      }
      this.showType = "devDelete";
    },
    showParamsDlg(dev) {
      this.$set(this.page, "index", 1);
      this.paramsVisible = true;
      this.curDevParam = dev.deviceid;
      this.getParams();
      this._getVarTypes();
    },
    addDev() {
      this.showDlg = true;
      if (this.curDev) {
        this.curDevInfo = {
          channel: this.curWay || null,
          prioritylevel: 3,
          resendcount: 1,
          breakcount: 1,
          numareacount: 1
        };
        this.curDev = null;
      }
      this.devTpls = null;
      this.devChildren = null;
    },
    async editDev(r) {
      this.showDlg = true;
      if (this.curDev !== r.deviceid) {
        this.curDev = r.deviceid;
        await this.getDeviceInfo();
        this.groupChange(this.curDevInfo.devicegroupid, true);
        this._getDevChildren(this.curDevInfo.devicetempid);
      }
    },
    saveDevInfo(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const post = clone(this.curDevInfo);
          console.log("提交数据", post)
          this.$confirm("确定保存?", "提示").then(() => {
            const load = this.$loading();
            return this.$axios
              .post("fes/device/edit", post)
              .then(res => {
                if (res.code === 1) {
                  this.$message.success("保存成功!");
                  this.$set(this.devInfo, this.curDev, this.curDevInfo);
                  this.showDlg = false;
                  this.curDev = false;
                  this.$emit("devChange");
                  location.reload()
                  // 刷新列表
                  // this.$nextTick(function () {
                  //   this.tableData()
                  // })
                } else {
                  throw res.msg;
                }
              })
              .catch(e => {
                this.$message.error(e);
              })
              .finally(() => {
                load.close();
              });
          });
        } else {
          this.$notify({
            title: '警告',
            message: '必填项不能为空',
            type: 'warning'
          });
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    cancleSave() {
      this.curDev && (this.curDevInfo = clone(this.devInfo[this.curDev]));
      this.showDlg = false;
    },
    deleteDev(r) {
      this.$confirm(
        "删除设备可能导致某些应用错误，确定删除该设备吗？",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(() => {
          const load = this.$loading();
          this.$axios
            .post("fes/device/removeDev", { deviceid: r.deviceid })
            .then(res => {
              if (res.code === 1) {
                this.$emit("devChange");
                this.curDev = null;
              } else {
                throw res.msg;
              }
              location.reload()
            })
            .catch(e => {
              this.$message.error(e);
            })
            .finally(() => {
              load.close();
            });
        })
        .catch(() => {});
    },

    // data
    _getVarTypes() {
      if (this.varTypes) return;
      this.$axios
        .get("fes/drop/queryVrdatanew")
        .then(res => {
          if (res.code === 1) {
            console.log(res)
            this.varTypes = res.data;
          } else {
            throw res.msg;
          }
        })
        .catch(e => this.$message.error(e));
    },
    getVarType(type) {
      if (!this.varTypes) return null;
      const a = this.varTypes.filter(e => e.variabletype === type)[0];
      return a && a.variablename;
    },
    _getVarLens() {
      if (this.varLens) return;
      this.$axios
        .get("fes/drop/queryProtocoltype?table=fes_datalength")
        .then(res => {
          if (res.code === 1) {
            this.varLens = res.data;
          } else {
            throw res.msg;
          }
        })
        .catch(e => this.$message.error(e));
    },
    _getVarCodes() {
      if (this.varCodes) return;
      this.$axios
        .get("fes/drop/queryProtocoltype?table=fes_datacodetype")
        .then(res => {
          if (res.code === 1) {
            this.varCodes = res.data;
          } else {
            throw res.msg;
          }
        })
        .catch(e => this.$message.error(e));
    },
    _getDcType() {
      if (this.dctypes) return;
      return this.$axios
        .get("fes/drop/queryDataacqtype")
        .then(res => {
          if (res.code === 1) {
            this.dctypes = res.data;
          } else {
            throw res.msg;
          }
        })
        .catch();
    },
    editData(r) {
      console.log("111", r)
      this._getVarTypes();
      this._getVarLens();
      this._getVarCodes();
      this._getDcType();
      this.newData = r;
      this.dataDlg = true;
    },
    deleteData(r) {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        return delData(r.pkid)
          .then(() => {
            this.getParams();
          })
          .catch(e => this.$message.error(e));
      });
    },
    saveData() {
      const load = this.$loading();
      console.log("variabletype", this.newData.variabletype[1])
      const Ndata = {
        createTime: this.newData.createTime,
        dataType: this.newData.dataType,
        dataareaid: this.newData.dataareaid,
        datacodeid: this.newData.datacodeid,
        dctype: this.newData.dctype,
        deviceid: this.newData.deviceid,
        length: this.newData.length,
        maxValue: this.newData.maxValue,
        number: this.newData.number,
        pkid: this.newData.pkid,
        ratio: this.newData.ratio,
        rcAddress: this.newData.rcAddress,
        rcAddressStr: this.newData.rcAddressStr,
        realType: this.newData.realType,
        stationId: this.newData.stationId,
        status: this.newData.status,
        tmpValue: this.newData.tmpValue,
        updateTime: this.newData.updateTime,
        variablename: this.newData.variablename,
        variabletype: this.newData.variabletype[1],
        xuhao: this.newData.xuhao
      }
      return editData(Ndata)
        .then(() => {
          this.getParams();
          this.newData = null;
          this.dataDlg = false;
        })
        .catch(e => {
          console.log(e);
          this.$message.error(e);
        })
        .finally(() => load.close());
    }
  }
};
</script>

<style lang="scss" scoped>
@import "~@/styles/variables.scss";
.sb-content {
  position: relative;
  margin: 0 auto;
  .warn-tip {
    max-width: 100%;
    width: 460px;
    border: 1px dotted $warn-color;
    padding: 20px;
    color: $warn-color;
    margin: 20px 0 0 0;
    position: relative;
    .title {
      position: absolute;
      z-index: 9;
      top: 0;
      background: #083554;
      left: 20px;
      transform: translateY(-50%);
      padding: 4px 10px;
    }
    .text-row {
      display: flex;
      line-height: 24px;
      span {
        flex-shrink: 0;
      }
      p {
        text-align: left;
      }
    }
    p {
      display: inline-block;
    }
  }
  .input-row {
    .el-checkbox {
      display: inline !important;
    }
    .tip {
      left: 150px !important;
    }
  }
}
.devAddDlg {
  .sb-content {
    margin: 0;
    padding: 10px;
    width: auto;
    .left,
    .right {
      width: 50%;
    }
    .top .input-row {
      margin-right: 20px;
    }
    .warn-tip {
      box-sizing: border-box;
    }
  }
}
</style>
